package online.sixfish.doubao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import online.sixfish.common.pojo.User;
import online.sixfish.doubao.mapper.BmsCommentMapper;
import online.sixfish.doubao.model.dto.CommentDTO;
import online.sixfish.doubao.model.entity.Comment;
import online.sixfish.doubao.model.vo.CommentVO;
import online.sixfish.doubao.service.IBmsCommentService;
import lombok.extern.slf4j.Slf4j;
import online.sixfish.doubao.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Slf4j
@Service
@Primary
public class IBmsCommentServiceImpl extends ServiceImpl<BmsCommentMapper, Comment> implements IBmsCommentService {
    @Resource
    UserService userService;

    @Override
    public List<CommentVO> getCommentsByTopicID(String topicid) {
        List<CommentVO> lstBmsComment = new ArrayList<>();
        try {
            LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Comment::getTopicId, topicid);
            List<Comment> comments = this.baseMapper.selectList(wrapper);
            for (int i = 0; i < comments.size(); i++) {
                CommentVO commentVO = new CommentVO();
                User user = userService.findById(comments.get(i).getUserId());
                commentVO.setUsername(user.getUsername());
                commentVO.setUserId(user.getId());
                commentVO.setAvatar(user.getAvatar());
                BeanUtils.copyProperties(comments.get(i),commentVO);
                lstBmsComment.add(commentVO);
            }
        } catch (Exception e) {
            log.info("lstBmsComment失败");
        }
        return lstBmsComment;
    }

    @Override
    public Comment create(CommentDTO dto, User user) {
        Comment comment = Comment.builder()
                .userId(user.getId())
                .content(dto.getContent())
                .topicId(dto.getTopic_id())
                .createTime(new Date())
                .build();
        this.baseMapper.insert(comment);
        return comment;
    }
}
